package zheezes.protocol.impl.gd.bean;

import zheezes.util.ArrayUtil;
import zheezes.util.ByteUtil;

public class MeterData {
	private byte[] no = new byte[6];
	private byte size;
	private short state;
	private AbstractMeterData data;
	
	public int size() {
		int size = 9;
		size += data.size();
		return size;
	}

	public int setBytes(byte[] buf, int offset, int max) {
		int idx = offset;
		System.arraycopy(buf, idx, no, 0, 6);
		ArrayUtil.reverse(no);
		idx += 6;
		size = buf[idx++];
		state = ByteUtil.ctos(buf, idx);
		idx += 2;
		byte[] tmp = new byte[size - 2];
		System.arraycopy(buf, idx, tmp, 0, tmp.length);
		switch (size - 2) {
			case 4 :
				data = new SimpleMeterData(tmp);
				break;
			case 20 :
				// TODO
				break;
			default :
				return -1;
		}
		idx += size - 2;
		return idx - offset;
	}
	
	public int setBytes(byte[] buf) {
		return setBytes(buf, 0, buf.length);
	}
	
	public byte[] getBytes() {
		byte[] buf = new byte[7 + size];
		int idx = 0;
		System.arraycopy(no, 0, buf, idx, 6);
		ArrayUtil.reverse(buf, idx, 6);
		idx += 6;
		buf[idx++] = size;
		ByteUtil.stoc(buf, idx, state);
		idx += 2;
		byte[] tmp = data.getBytes();
		ArrayUtil.reverse(tmp);
		System.arraycopy(tmp, 0, buf, idx, tmp.length);
		return buf;
	}

	public byte[] getNo() {
		return no;
	}

	public void setNo(byte[] no) {
		System.arraycopy(no, 0, this.no, 0, no.length);
	}

	public short getState() {
		return state;
	}

	public void setState(short state) {
		this.state = state;
	}

	public AbstractMeterData getData() {
		return data;
	}

	public void setData(AbstractMeterData data) {
		this.data = data;
	}
}
